import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class StudentRecord {
    private String name;
    private String studentId;
    private String course;
    private double score;

    public StudentRecord(String name, String studentId, String course, double score) {
        this.name = name;
        this.studentId = studentId;
        this.course = course;
        this.score = score;
    }

    // Getters
    public String getName() {
        return name;
    }

    public String getStudentId() {
        return studentId;
    }

    public String getCourse() {
        return course;
    }

    public double getScore() {
        return score;
    }
}

class StatisticsResult {
    private String course;
    private double average;
    private double max;
    private double min;
    private int count;

    public StatisticsResult(String course, double average, double max, double min, int count) {
        this.course = course;
        this.average = average;
        this.max = max;
        this.min = min;
        this.count = count;
    }

    // Getters
    public String getCourse() {
        return course;
    }

    public double getAverage() {
        return average;
    }

    public double getMax() {
        return max;
    }

    public double getMin() {
        return min;
    }

    public int getCount() {
        return count;
    }
}

class StudentGradeSystem {
    private String dataFile;
    private List<StudentRecord> studentRecords;

    public StudentGradeSystem(String dataFile) {
        this.dataFile = dataFile;
        this.studentRecords = loadData();
    }

    public StudentGradeSystem() {
        this("grades.json");
    }

    private List<StudentRecord> loadData() {
        List<StudentRecord> records = new ArrayList<>();
        File file = new File(dataFile);

        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] parts = line.split(",");
                    if (parts.length == 4) {
                        String name = parts[0];
                        String studentId = parts[1];
                        String course = parts[2];
                        double score = Double.parseDouble(parts[3]);
                        records.add(new StudentRecord(name, studentId, course, score));
                    }
                }
            } catch (IOException | NumberFormatException e) {
                System.out.println("警告：无法加载数据文件 " + dataFile + "，将使用空数据");
            }
        }
        return records;
    }

    private void saveData() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(dataFile))) {
            for (StudentRecord record : studentRecords) {
                writer.write(String.format("%s,%s,%s,%.1f\n",
                        record.getName(),
                        record.getStudentId(),
                        record.getCourse(),
                        record.getScore()));
            }
        } catch (IOException e) {
            System.out.println("错误：无法保存数据到文件 " + dataFile);
        }
    }

    public String recordGrade(String name, String studentId, String course, double score) {
        if (score < 0 || score > 100) {
            return "错误：成绩必须在0-100分之间";
        }

        for (StudentRecord record : studentRecords) {
            if (record.getStudentId().equals(studentId) && record.getCourse().equals(course)) {
                return "错误：该学生的该课程成绩已存在";
            }
        }

        studentRecords.add(new StudentRecord(name, studentId, course, score));
        saveData();
        return "成绩已成功记录！";
    }

    public Object queryGrade(int queryType, String queryValue) {
        List<StudentRecord> results = new ArrayList<>();
        for (StudentRecord record : studentRecords) {
            switch (queryType) {
                case 1:
                    if (record.getName().equals(queryValue)) {
                        results.add(record);
                    }
                    break;
                case 2:
                    if (record.getStudentId().equals(queryValue)) {
                        results.add(record);
                    }
                    break;
                case 3:
                    if (record.getCourse().equals(queryValue)) {
                        results.add(record);
                    }
                    break;
                default:
                    return "错误：无效的查询类型";
            }
        }

        if (results.isEmpty()) {
            return "未找到相关成绩记录";
        }
        return results;
    }

    public Object statisticsGrade(String course) {
        List<StudentRecord> courseRecords = new ArrayList<>();
        for (StudentRecord record : studentRecords) {
            if (record.getCourse().equals(course)) {
                courseRecords.add(record);
            }
        }

        if (courseRecords.isEmpty()) {
            return "未找到该课程的成绩记录";
        }

        double sum = 0;
        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;

        for (StudentRecord record : courseRecords) {
            double score = record.getScore();
            sum += score;
            if (score > max) {
                max = score;
            }
            if (score < min) {
                min = score;
            }
        }

        double average = sum / courseRecords.size();
        return new StatisticsResult(course,
                (double) Math.round(average * 100) / 100,
                max,
                min,
                courseRecords.size());
    }
}

public class Main {
    public static void clearScreen() {
        System.out.print("\033[H\033[2J");
        System.out.flush();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StudentGradeSystem system = new StudentGradeSystem();

        while (true) {
            clearScreen();
            System.out.println("=================================");
            System.out.println("欢迎使用学生成绩管理系统");
            System.out.println("=================================");
            System.out.println("请选择操作：");
            System.out.println("1. 记录学生成绩");
            System.out.println("2. 查询学生成绩");
            System.out.println("3. 统计课程成绩");
            System.out.println("4. 退出系统");
            System.out.print("请输入选项序号：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    clearScreen();
                    System.out.println("===== 记录学生成绩 =====");
                    System.out.print("请输入学生姓名：");
                    String name = scanner.nextLine();
                    System.out.print("请输入学生学号：");
                    String studentId = scanner.nextLine();
                    System.out.print("请输入课程名称：");
                    String course = scanner.nextLine();

                    try {
                        System.out.print("请输入成绩（0-100）：");
                        double score = Double.parseDouble(scanner.nextLine());
                        String result = system.recordGrade(name, studentId, course, score);
                        System.out.println(result);
                    } catch (NumberFormatException e) {
                        System.out.println("错误：成绩必须为数字");
                    }
                    System.out.println("\n按Enter键返回主菜单...");
                    scanner.nextLine();
                    break;

                case "2":
                    clearScreen();
                    System.out.println("===== 查询学生成绩 =====");
                    System.out.println("请选择查询方式：");
                    System.out.println("1. 按学生姓名查询");
                    System.out.println("2. 按学生学号查询");
                    System.out.println("3. 按课程名称查询");
                    System.out.print("请输入选项序号：");

                    try {
                        int queryChoice = Integer.parseInt(scanner.nextLine());
                        if (queryChoice >= 1 && queryChoice <= 3) {
                            System.out.print("请输入查询值：");
                            String queryValue = scanner.nextLine();
                            Object results = system.queryGrade(queryChoice, queryValue);

                            if (results instanceof String) {
                                System.out.println(results);
                            } else {
                                @SuppressWarnings("unchecked")
                                List<StudentRecord> records = (List<StudentRecord>) results;
                                System.out.println("\n查询结果：");
                                for (StudentRecord record : records) {
                                    System.out.printf("姓名：%s, 学号：%s, 课程：%s, 成绩：%.1f\n",
                                            record.getName(),
                                            record.getStudentId(),
                                            record.getCourse(),
                                            record.getScore());
                                }
                            }
                        } else {
                            System.out.println("错误：选项序号必须为1-3");
                        }
                    } catch (NumberFormatException e) {
                        System.out.println("错误：选项序号必须为数字");
                    }
                    System.out.println("\n按Enter键返回主菜单...");
                    scanner.nextLine();
                    break;

                case "3":
                    clearScreen();
                    System.out.println("===== 统计课程成绩 =====");
                    System.out.print("请输入课程名称：");
                    String courseName = scanner.nextLine();
                    Object result = system.statisticsGrade(courseName);

                    if (result instanceof String) {
                        System.out.println(result);
                    } else {
                        StatisticsResult stats = (StatisticsResult) result;
                        System.out.printf("\n课程：%s\n", stats.getCourse());
                        System.out.printf("学生数量：%d\n", stats.getCount());
                        System.out.printf("平均分：%.2f\n", stats.getAverage());
                        System.out.printf("最高分：%.1f\n", stats.getMax());
                        System.out.printf("最低分：%.1f\n", stats.getMin());
                    }
                    System.out.println("\n按Enter键返回主菜单...");
                    scanner.nextLine();
                    break;

                case "4":
                    System.out.println("感谢使用学生成绩管理系统，再见！");
                    scanner.close();
                    return;

                default:
                    System.out.println("错误：无效的选项，请重新输入");
                    System.out.println("\n按Enter键继续...");
                    scanner.nextLine();
            }
        }
    }
}    